﻿using Newtonsoft.Json.Linq;
using System;
using System.Data;
using System.Data.SQLite;
using System.IO;
using System.Net;
using System.Text;
using System.Threading;
using System.Windows.Forms;


namespace Change
{
    public partial class ucPrice : UserControl
    {
        SQLiteConnection conn;
        //定义委托
        delegate void inittvItemsDelegate();
        delegate void AsynUpdateUI1(string step);   //更新UI1
        delegate void AsynUpdateUI2(TreeNode root);//更新UI2

        public delegate void UpdateUI(string step);//声明一个更新主线程的委托
        public UpdateUI UpdateUIDelegate;

        public delegate void AccomplishTask(TreeNode root);//声明一个在完成任务时通知主线程的委托
        public AccomplishTask TaskCallBack;

        public ucPrice()
        {
            InitializeComponent();


            twItems.Nodes.Add("正在连接数据库");
            UpdateUIDelegate += UpdataUIStatus;//绑定更新任务状态的委托
            TaskCallBack += Accomplish;//绑定完成任务要调用的委托
            //启动线程
            Thread thread = new Thread(intitvItems);
            thread.IsBackground = true;
            thread.Start();
            //intitvItems();
        }


        //更新UI
        private void UpdataUIStatus(string step)
        {
            if (InvokeRequired)
            {
                this.Invoke(new AsynUpdateUI1(delegate (string s)
                {
                    //this.pgbWrite.Value += s;
                    //this.lblWriteStatus.Text = this.pgbWrite.Value.ToString() + "/" + this.pgbWrite.Maximum.ToString();
                    twItems.Nodes.Add(s);
                }), step);
            }
        }

        //完成任务时需要调用
        private void Accomplish(TreeNode root)
        {
            if (InvokeRequired)
            {
                this.Invoke(new AsynUpdateUI2(delegate (TreeNode rt)
                {
                    //this.pgbWrite.Value += s;
                    //this.lblWriteStatus.Text = this.pgbWrite.Value.ToString() + "/" + this.pgbWrite.Maximum.ToString();
                    twItems.Nodes.Clear();
                    twItems.Nodes.Add(rt);
                }), root);
            }
        }
        private void ucPrice_Load(object sender, System.EventArgs e)
        {
            
        }
        private void  intitvItems()
        {
            TreeNode root = new TreeNode();
            root.Tag = 0;
            root.Text = "物品数据库-"+ "YC122";
            root.Expand();
            //   twItems.Nodes.Add(root);
          try
          {
            conn = new SQLiteConnection("Data Source=db/eve.db;Version=3;");
            conn.Open();

            UpdateUIDelegate("数据库已连接，正在加载数据...");
          }
          catch(Exception ex)
            {
                throw ex;
            }
               

            setTreeView(root, 0);
            UpdateUIDelegate("市场组数据加载完毕，正在加载物品数据");
            setTreeViewLeaf(root);
            UpdateUIDelegate("物品组数据加载完毕.");
            TaskCallBack(root);
            
        }
       /// <summary>
       /// 查找叶子节点
       /// </summary>
       /// <param name="tr1"></param>
        private void setTreeViewLeaf(TreeNode tr1)
        {
           
            foreach(TreeNode node in tr1.Nodes)
            {
                //查找树的叶子节点
                if(node.Nodes.Count==0)
                {
                    addNodeLeaf(node);
                     
                }
                else
                {
                    findTreeViewLeaf(node);
                }
                UpdateUIDelegate("加载物品组"+node.Text);
            }  
        }
        /// <summary>
        /// 第二层遍历，加速函数
        /// </summary>
        /// <param name="tr1"></param>
        private void findTreeViewLeaf(TreeNode tr1)
        {
            foreach (TreeNode node in tr1.Nodes)
            {
                //查找树的叶子节点
                if (node.Nodes.Count == 0)
                {
                    addNodeLeaf(node);

                }
                else
                {
                    flashTreeViewLeaf(node);
                }

            }
        }
        /// <summary>
        /// 第三层遍历，加速函数
        /// </summary>
        /// <param name="node"></param>
        private void flashTreeViewLeaf(TreeNode tr1)
        {
            foreach (TreeNode node in tr1.Nodes)
            {
                //查找树的叶子节点
                if (node.Nodes.Count == 0)
                {
                    addNodeLeaf(node);

                }
                else
                {
                    flashTreeViewLeaf(node);
                }

            }
        }


        /// <summary>
        /// 添加叶子节点
        /// </summary>
        /// <param name="node"></param>
        private void addNodeLeaf(TreeNode node)
        {
            int pid = Convert.ToInt32(node.Tag);

            string sql = "select typeID,typeName_zh from invtypes where marketGroupID="+pid;

            SQLiteDataAdapter reader = new SQLiteDataAdapter(sql, conn);
             
            DataTable dtLeaf = new DataTable();

            reader.Fill(dtLeaf);
            if (dtLeaf.Rows.Count > 0)
            {
                foreach(DataRow dr in dtLeaf.Rows)
                {
                    TreeNode nodeleaf = new TreeNode();
                    nodeleaf.Text = dr[1].ToString();
                    nodeleaf.Tag = Convert.ToInt32(dr[0]);
                
                    node.Nodes.Add(nodeleaf);
                }
            }
        }

        private void setTreeView(TreeNode tr1, int parentId)
        {
            string sql;
            if (parentId == 0)
                sql = "select marketGroupID,marketGroupName_zh,parentGroupID from invmarketgroups where parentGroupID is null";
            else
                sql = "select marketGroupID,marketGroupName_zh,parentGroupID from invmarketgroups where parentGroupID=" + parentId;
            SQLiteDataAdapter reader = new SQLiteDataAdapter(sql, conn);

            DataTable dt = new DataTable();
            reader.Fill(dt);

            if (dt.Rows.Count > 0)
            {
                
                int pId = -1;
                  foreach (DataRow row in dt.Rows)
                  {
                         TreeNode node = new TreeNode();
                         node.Text = row[1].ToString();                     
                         node.Tag =  Convert.ToInt32(row[0]);
                         if (row[2] is System.DBNull)
                            pId = 0;
                         else
                                pId = Convert.ToInt32(row[2]);
                         if (pId == 0)
                          {
                              //添加根节点
                              tr1.Nodes.Add(node);
                          }
                          else
                          {
                              //添加根节点之外的其他节点
                              RefreshChildNode(tr1, node, pId);
                          }
                          //查找以node为父节点的子节点
                          setTreeView(tr1, Convert.ToInt32(node.Tag));
 
                  }
             }
 
         }
        //处理根节点的子节点
        private void RefreshChildNode(TreeNode tr1, TreeNode treeNode, int parentId)
        {
                    foreach (TreeNode node in tr1.Nodes)
                            {
                                if (Convert.ToInt32(node.Tag) == parentId)
                                    {
                                        node.Nodes.Add(treeNode);
                                        return;
                                    }else if (node.Nodes.Count > 0)
                                    {
                                        FindChildNode(node, treeNode, parentId);
                                    }
                            }
            }
 
        //处理根节点的子节点的子节点
        private void FindChildNode(TreeNode tNode, TreeNode treeNode, int parentId)
       {
                   foreach (TreeNode node in tNode.Nodes)
                        {
                              if (Convert.ToInt32(node.Tag) == parentId)
                                 {
                                      node.Nodes.Add(treeNode);
                                     return;
                                 }else if (node.Nodes.Count > 0)
                                 {
                                      FindChildNode(node, treeNode, parentId);
                                  }
       
                     }
   
        }

        private void btConfirm_Click(object sender, EventArgs e)
        {
            
        }


        private void twItems_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            string buyitem, sellitem;
            int typeID = Convert.ToInt32(e.Node.Tag);
            string retString = null;

            string url = "http://www.ceve-market.org/api/market/region/10000002/system/30000142/type/" + typeID + ".json";   //国服市场中心API的URL
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Proxy = null;
                request.KeepAlive = false;
                request.Method = "GET";
                request.ContentType = "application/json; charset=UTF-8";

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream rs = response.GetResponseStream();
                StreamReader sr = new StreamReader(rs, Encoding.UTF8);
                retString = sr.ReadToEnd();
                rs.Close();
                sr.Close();
            }catch(WebException ex)
            {
                MessageBox.Show("错误："+ex);
                throw ex;
            }


            JObject price = JObject.Parse(retString);
            JObject sell = (JObject)price["sell"];
            JObject buy = (JObject)price["buy"];
            string sel = (string)sell["min"];
            string bu = (string)buy["max"]; //JSON转化
            //long lsell = (long)sell["volume"];
            //DateTime dtsell = new DateTime(lsell);
            //long lbuy = (long)buy["volume"];
            //DateTime dtbuy= new DateTime(lbuy);

            if (sel==null)
            {
                sellitem = " ";
            }
            else
            {
                  
                sellitem = string.Format("{0:0,0.00}",float.Parse(sel));
            }
            if (bu == null)
            {
                buyitem = " ";
            }
            else
            {
                buyitem = string.Format("{0:0,0.00}", float.Parse(bu));
            }
            int index = this.dgbPrice.Rows.Add();
            dgbPrice.Rows[index].Cells[0].Value = 1;
            dgbPrice.Rows[index].Cells[1].Value = e.Node.Text;
            dgbPrice.Rows[index].Cells[2].Value = sellitem;
            //dgbPrice.Rows[index].Cells[3].Value = dtsell.ToString("f");
            dgbPrice.Rows[index].Cells[3].Value = buyitem;
            //dgbPrice.Rows[index].Cells[5].Value = dtbuy.ToString("f");     
        }

    }
}
